package com.task.scheduler.config;

import com.task.scheduler.executor.TaskExecutor;
import com.task.scheduler.queue.RedissonTaskQueueService;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.redisson.Redisson;

import java.util.List;

/**
 * 自动配置类
 * 支持 Spring Boot 项目自动装配 Redisson 和 TaskExecutor
 */
@Configuration
@ComponentScan("com.task.scheduler") // 扫描所有模块
@EnableJpaAuditing // 启用JPA审计功能
public class TaskSchedulerAutoConfiguration {

    @Bean
    public TaskSchedulerProperties redissonProperties() {
        return new TaskSchedulerProperties();
    }

    /**
     * 如果没有外部配置 RedissonClient，则创建一个默认实例
     */
    @Bean
    @ConditionalOnMissingBean
    public RedissonClient redissonClient(TaskSchedulerProperties properties) {
        Config config = new Config();
        String address = "redis://" + properties.getRedisson().getHost() + ":" + properties.getRedisson().getPort();

        config.useSingleServer()
                .setAddress(address)
                .setPassword(properties.getRedisson().getPassword());

        return Redisson.create(config);
    }

    /**
     * 创建任务队列服务
     * 需要 RedissonClient、TaskExecutor 和 ApplicationEventPublisher
     */
    @Bean
    public RedissonTaskQueueService redissonTaskQueueService(
            RedissonClient redissonClient,
            List<TaskExecutor> executors,
            ApplicationEventPublisher publisher) {
        RedissonTaskQueueService service = new RedissonTaskQueueService(redissonClient, executors, publisher);
        return service;
    }
}
